Literals and Escape Sequence in C++

Posted on December 4, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

Literal is a notation for representing a fixed value in source code. Literals can be used to express constants of various types, such as integers, floating-point numbers, characters, and strings. C++ supports several types of literals, and each type has its own syntax.

Here are some common types of literals in C++:

1. Integer Literals:

int decimalLiteral = 42;
int octalLiteral = 052; // Octal (prefix 0)
int hexadecimalLiteral = 0x2A; // Hexadecimal (prefix 0x or 0X)

2. Floating-point Literals:

double standardFloatLiteral = 3.14;
double scientificFloatLiteral = 2.0e5;// 2.0 * 10^5

3. Character Literals:

char singleCharLiteral = 'A';
char escapeCharLiteral = '\n'; // Newline character

4. String Literals:

const * stringLiteral = "Hello, World!";

5. Boolean Literals:

bool trueLiteral = true;
bool trufalseLiteraleLiteral = false;

Escape Sequence

Escape sequence is a special combination of characters that starts with a backslash \ and is used to represent special characters or actions within strings. For example, \n represents a newline, \t represents a tab, \" represents a double quote, and so on. Escape sequences make it easier to include certain characters in strings.

Escape Sequence in C++ in C++

Example of Escape Sequence:-

#include<iostream>Copy Code

int main() {
    std::cout << "Hello, World!\nThis is a new line.\n";
    std::cout << "This\tis\ttab\tseparated.\n";
    std::cout << "This is a backslash: \\ and this is a quote: \"\n";
    return 0;
}